﻿using System;
using System.Windows.Forms;
using YaP.Library;

namespace YaP.Forms
{
    public partial class NewServerForm : Form
    {
        private Guid GroupID;
        private FormAction innerAction;
        private FormOpenMode OpenMode;
        private Guid ServerID;

        public NewServerForm(string _grname, Guid _GroupID)
        {
            InitializeComponent();
            lblGroup.Text = _grname;
            GroupID = _GroupID;
            OpenMode = FormOpenMode.New;
        }

        public NewServerForm(Guid _ServID, Guid _GroupID)
        {
            InitializeComponent();
            GroupID = _GroupID;
            ServerID = _ServID;
            ServerFactory srvFact = new ServerFactory();
            lblGroup.Text = srvFact.GetGroup(_GroupID).NetworkName;
            ServerItem MyServer = srvFact.GetServer(_ServID, _GroupID);
            txtAdd.Text = MyServer.ServerHost;
            txtName.Text = MyServer.ServerName;
            txtPort.Text = MyServer.ServerPort.ToString();
            OpenMode = FormOpenMode.Edit;
        }

        public FormAction Action
        {
            get { return innerAction; }
        }

        private void frmNewServ_Load(object sender, EventArgs e)
        {
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            bool nameOk = (txtName.Text != string.Empty);
            bool addOk = (txtAdd.Text != string.Empty);
            bool portOk;
            try
            {
                int.Parse(txtPort.Text);
                portOk = true;
            }
            catch (Exception)
            {
                portOk = false;
            }
            if ((nameOk) && (addOk) && (portOk))
            {
                Library.ServerFactory ServFact = new YaP.Library.ServerFactory();
                if (OpenMode == FormOpenMode.New)
                    ServFact.AddServer(txtName.Text, txtAdd.Text, int.Parse(txtPort.Text), GroupID);
                else
                    ServFact.EditServer(txtName.Text, txtAdd.Text, int.Parse(txtPort.Text), GroupID, ServerID);

                ServFact.Save();
                innerAction = FormAction.Ok;
                Close();
            }
            else
            {
                MessageBox.Show("these settings are not valid", "Error!");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            innerAction = FormAction.Cancel;
            Close();
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }
    }
}